package com.llkj.qingnianguoxue.book;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.BookVideoAdapter;
import com.llkj.qingnianguoxue.base.BaseFragment;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.BookVideoBean;
import com.llkj.qingnianguoxue.bean.BookVideoListBean;
import com.llkj.qingnianguoxue.bean.BuyVideoBean;
import com.llkj.qingnianguoxue.bean.EventChangeUserBean;
import com.llkj.qingnianguoxue.bean.HomeModuleBean;
import com.llkj.qingnianguoxue.bean.response.ResponseList;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;
import com.sevenheaven.iosswitch.ShSwitchView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

import static com.llkj.qingnianguoxue.home.VideoDetailActivity.REFRESH_STATE;

/**
 * 订阅视频
 */
public class BookVideoFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    private static final int REQUEST_VIDEO_CODE = 7965;
    @BindView(R.id.sw_open)
    protected ShSwitchView mHideSwitch;//隐藏开关
    @BindView(R.id.refresh_layout)
    protected SwipeRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    protected RecyclerView lvActions;
    private BookVideoAdapter videoAdapter;
    private List<BookVideoListBean.CategoryBean> mVideosData;
    private int totalSize, mPage, mCurrentPosition;
    private String is_hide = "2";//是1 否2 隐藏已看完

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_book_video, container, false);
        ButterKnife.bind(this,rootView);
        EventBus.getDefault().register(this);

        initView();
        initListener();

        loadWaitDialog();
        onRefresh();
        return rootView;
    }

    private void initView() {
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvActions.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL,false));

        mVideosData = new ArrayList<>();
//        videoAdapter = new BookVideoAdapter(R.layout.item_book_video, mVideosData);
        videoAdapter = new BookVideoAdapter(R.layout.item_subscribe_video_book, mVideosData);
        videoAdapter.setType(1);
        lvActions.setAdapter(videoAdapter);
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(this);
        videoAdapter.setOnLoadMoreListener(this);
        mHideSwitch.setOnSwitchStateChangeListener(new ShSwitchView.OnSwitchStateChangeListener() {
            @Override
            public void onSwitchStateChange(boolean isOn) {
                if(isOn){
                    is_hide = "1";
                }else{
                    is_hide = "2";
                }
                onRefresh();
            }
        });
        RxBus.getInstance().toObservable(String.class).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                if (s.equals(REFRESH_STATE)){
                    onRefresh();
                }
            }
        });
//        lvActions.addOnItemTouchListener(new OnItemClickListener() {
//            @Override
//            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
//                mCurrentPosition = i;
//                BookVideoListBean.BookVideoBean item = mVideosData.get(i);
//                Bundle bundle = new Bundle();
//                bundle.putString("id", item.getId());
//                bundle.putString("type", "1");//有接口后，不需要了
//                bundle.putBoolean(ConstantUserInfo.GONE, true);//有接口后，不需要了
//                startActivityForResult(VideoDetailActivity.class, bundle, REQUEST_VIDEO_CODE);
//            }
//        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (getActivity().RESULT_OK == resultCode && requestCode == REQUEST_VIDEO_CODE && data != null) {
            onRefresh();
//            if (data.hasExtra("percent")) {
//                BookVideoListBean.BookVideoBean item = mVideosData.get(mCurrentPosition);
//                item.setPlays_percent(data.getStringExtra("percent"));
//                videoAdapter.notifyItemChanged(mCurrentPosition);
//            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeUser(EventChangeUserBean event){
        onRefresh();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getVideoData();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getVideoData();
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, videoAdapter, null, lvActions, totalSize);
    }

    private void getVideoData() {
        HttpMethod.userbuyVideo(getActivity(), this, is_hide, String.valueOf(mPage),"");
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_USER_USERBUY_VIDEO) {
            ResponseList<BuyVideoBean> hotRankingBean = GsonUtil.fromJsonList(data, BuyVideoBean.class);
            if (hotRankingBean != null) {
                try{
                    totalSize = Integer.parseInt(hotRankingBean.getNum());
                }catch (Exception e){}

                if (mPage == 1) {
                    mVideosData.clear();
                    LoadDataHelper.refreshComplete(videoAdapter, mVideosData, refreshLayout, lvActions);
                } else {
                    videoAdapter.setEnableLoadMore(true);
                    videoAdapter.loadMoreComplete();
                }
                videoAdapter.loadMoreEnd();

                List<BuyVideoBean> list = hotRankingBean.getVideo();
                if(list != null){
                    BuyVideoBean buyVideoBean = null;
                    BookVideoListBean.CategoryBean categoryBean = null;
                    for(int i=0;i<list.size();i++){
                        buyVideoBean = list.get(i);
                        boolean isHas = false;
                        for(int j=0;j<mVideosData.size();j++){
                            categoryBean = mVideosData.get(j);
                            if(buyVideoBean.getClassify().equals(categoryBean.getCategoryName())){
                                isHas = true;
                                break;
                            }
                        }
                        if(!isHas){
                            categoryBean = new BookVideoListBean.CategoryBean();
                            categoryBean.setCategoryName(buyVideoBean.getClassify());
                            mVideosData.add(categoryBean);
                        }
                        categoryBean.setCategoryList(buyVideoBean.getVideo());
                    }
                    videoAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
        refreshLayout.setRefreshing(false);
    }
}
